let HttpRequest = function (options) {
  let defaults = {
    type: 'get',
    headers: {},
    data: {},
    dataType: 'json',
    async: true,
    cache: false,
    beforeSend: function(){
		layer.load();
	},
    success: null,
    complete:function(){
        layer.closeAll("loading");
    },
    error: function(msg){
        layer.alert("请求失败",{icon:5});
    }
  };
  let o = $.extend({}, defaults, options);
  $.ajax({
    url: "http://localhost:8767/"+o.url,
    type: o.type,
    headers: {
      'Content-Type': o.contentType,
      'Authorization': o.token
    },
    data: o.data,
    dataType: o.dataType,
    async: o.async,
    beforeSend: function () {
      o.beforeSend && o.beforeSend();
    },
    success: function (res) {
      o.success && o.success(res);
    },
    complete: function () {
      o.complete && o.complete();
    },
    error: function (err) {
      o.error && o.error(err);
    }
  });
};

//登录
let loginHttp = function (options) {
  // 登入页无需携带token
  // 后台如果要求 Content-Type 
  if (options.type == 'post') {
    options.contentType = 'application/x-www-form-urlencoded';
  }

  HttpRequest(options);
};

//普通
let ajaxHttp = function (options) {
	if (options.type == 'post' || options.type == 'patch'){
		options.contentType = "application/json";
	}
  // 每次请求携带token
  options.token = localStorage.getItem('access_token');
  HttpRequest(options);
};

//文件上传
let fileHttp = function (options){
	// 每次请求携带token
	options.token = localStorage.getItem('access_token');
	let defaults = {
	  type: 'get',
	  headers: {},
	  data: {},
	  dataType: 'json',
	  async: true,
	  cache: false,
	  beforeSend: function(){
			layer.load();
		},
	  success: null,
	  complete:function(){
	      layer.closeAll("loading");
	  },
	  error: function(msg){
	      layer.alert("请求失败",{icon:5});
	  }
	};
	let o = $.extend({}, defaults, options);
	$.ajax({
	  url: "http://localhost:8767/"+o.url,
	  type: o.type,
	  headers: {
	    'Authorization': o.token
	  },
	  data: o.data,
	  dataType: o.dataType,
	  async: o.async,
	  contentType:false,
	  processData:false,
	  beforeSend: function () {
	    o.beforeSend && o.beforeSend();
	  },
	  success: function (res) {
	    o.success && o.success(res);
	  },
	  complete: function () {
	    o.complete && o.complete();
	  },
	  error: function (err) {
	    o.error && o.error(err);
	  }
	});
}

//form表单转json
function form2JsonStrWithOutFile(form) {
	var jsForm = form.get(0);
	var formData = new FormData(jsForm);
	var json = {};
	for (var [a, b] of formData.entries()) {
		if(b instanceof File){
			continue;
		}
		//这里是如果有多选框多个值使用逗号拼接
		if(json[a]){
			json[a] += ',' + b;
		}else{
			json[a] = b;
		}
	}
	return JSON.stringify(json);
}